﻿using System.Reflection;
using Autofac;
using Autofac.Extras.DynamicProxy;
using BaseRepository.Db;
using BaseService;
using Common;
using Common.ConfigModel;
using Extensions.Interceptor.Event;
using Module = Autofac.Module;

namespace PLC.API
{
    /// <summary>
    /// autofac 依赖注入的注册
    /// </summary>
    public class AutofacModule : Module
    {
        // 具体的注册
        protected override void Load(ContainerBuilder builder)
        {
            // 注入拦截器
            builder.RegisterType<EventIntercept>();
            // 基类
            builder.RegisterGeneric(typeof(BaseRepository<>))
                .As(typeof(IBaseRepository<>))
                .InstancePerLifetimeScope()
                .PropertiesAutowired();
            builder.RegisterGeneric(typeof(BaseService<>))
                .As(typeof(IBaseService<>))
                .InstancePerLifetimeScope()
                .PropertiesAutowired();
            var config = Appsettings.app<AutofacConfig>("Startup", "Autofac");
            if (config==null|| string.IsNullOrWhiteSpace(config.Repository)||string.IsNullOrWhiteSpace(config.Service))
            {
                throw new Exception("autofac 配置有误  请检查配置文件");
            }
            // 仓储
            builder.RegisterAssemblyTypes(Assembly.Load(config.Repository))
                .Where(p => p.FullName.EndsWith("Repository"))
                .AsImplementedInterfaces()
                .InstancePerLifetimeScope()
                .PropertiesAutowired(); //支持属性注入
                //.EnableInterfaceInterceptors();
            // 暂时没有拦截器
            //.InterceptedBy(typeof(MemoryCacheInterceptor));
            //服务
            builder.RegisterAssemblyTypes(Assembly.Load(config.Service))
                .Where(p => p.FullName.EndsWith("Service")&&!p.FullName.Contains("PLCService"))
                .AsSelf()
                .InstancePerLifetimeScope()
                .PropertiesAutowired()
                .EnableClassInterceptors()
                .InterceptedBy(typeof(EventIntercept));
            //.EnableInterfaceInterceptors() // 开始事件拦截器  接口和方法开启拦截器的 调用的方法是不一样的
            //.InterceptedBy(typeof(EventIntercept));
        }
    }
}
